package com.company.cloud.user.modules.mgr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.HttpContextUtils;
import com.company.cloud.user.modules.api.constant.UserOneSourceEnum;
import com.company.cloud.user.modules.api.constant.UserOneTypeEnum;
import com.company.cloud.user.modules.api.constant.UserRegisterWayEnum;
import com.company.cloud.user.modules.api.models.UserModel;
import com.company.cloud.user.modules.api.request.UserMgrQueryCust4PageParam;
import com.company.cloud.user.modules.api.request.UserMgrUpdateParam;
import com.company.cloud.user.modules.api.request.UserRegisterParam;
import com.company.cloud.user.modules.app.service.UserRegisterService;
import com.company.cloud.user.modules.base.entity.DeptInfo;
import com.company.cloud.user.modules.base.entity.UserInfo;
import com.company.cloud.user.modules.base.entity.UserRoleInfo;
import com.company.cloud.user.modules.base.service.DeptInfoService;
import com.company.cloud.user.modules.base.service.UserInfoService;
import com.company.cloud.user.modules.base.service.UserRoleInfoService;
import com.company.cloud.user.modules.cache.service.UserPermissionCacheService;
import com.company.cloud.user.modules.cache.service.UserRoleDeptTeamCacheService;
import com.company.cloud.user.modules.cache.utils.UserConvertUtils;
import com.company.cloud.user.modules.mgr.controller.req.UserMgrQuery4PageParam;
import com.company.cloud.user.modules.mgr.controller.req.UserMgrUpdatePasswordParam;
import com.company.cloud.user.modules.mgr.controller.req.UserMgrUpdateStateParam;
import com.company.cloud.user.modules.mgr.service.UserMgrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

@Log4j2
@Authc
@RestController
@RequestMapping("/mgr/admin/user")
@Api(tags = "User_Mgr_用户管理")
public class UserMgrController {

    @Autowired
    private UserInfoService userInfoService;
   /* @Autowired
    private AccountInfoService accountInfoService;*/
    @Autowired
    private UserPermissionCacheService userPermissionCacheService;

    @Autowired
    private UserMgrService userMgrService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private UserRoleInfoService userRoleInfoService;

    @Autowired
    private UserRegisterService userRegisterService;
    @Autowired
    private UserRoleDeptTeamCacheService userRoleDeptTeamCacheService;

    public UserMgrController() {
    }

    @PostMapping("/queryCustomer")
    @ApiOperation(value = "客户列表查询", response = UserModel.class)
    public BaseResult queryCustomer(@RequestBody UserMgrQueryCust4PageParam params) {
        UserMgrQuery4PageParam param = new UserMgrQuery4PageParam();
        param.setUserType(UserOneTypeEnum.Customer_User.getCode());
        param.setUserName(params.getUserName());
        param.setMobile(params.getMobile());
        param.setNickName(params.getNickName());
        param.setUserState(params.getUserState());
        return query(param);
    }


    @PostMapping("/query")
	@ApiOperation(value="用户列表查询", response=UserModel.class)
	public BaseResult query(@RequestBody UserMgrQuery4PageParam params) {
    	LoginSimpleUserInfo  userInfo= AuthContextUtils.getUser();
		IPage<UserInfo> page =userInfoService.page(
				new Page<UserInfo>(params.getPage(), params.getRows()),new QueryWrapper<UserInfo>()
				.eq("company_no", userInfo.getCompanyNo())
				.eq(StringUtils.hasText(params.getUserType()), "user_type_one", params.getUserType())
				.eq(StringUtils.hasText(params.getUserState()), "user_state",params.getUserState())
				.like(StringUtils.hasText(params.getUserName()), "user_name", params.getUserName())
				.like(StringUtils.hasText(params.getNickName()), "nick_name", params.getNickName())
				.likeRight(StringUtils.hasText(params.getMobile()), "mobile", params.getMobile())
				.orderByDesc("reg_time")
				);
        final String[] deptName = {""};
		Set<Integer> deptIds=new HashSet<Integer>();
		if(page!=null && !CollectionUtils.isEmpty(page.getRecords())) {
			for(UserInfo item:page.getRecords()) {
                List<UserRoleInfo> userRoleList= userRoleInfoService.list(
						new QueryWrapper<UserRoleInfo>().eq("user_id", item.getId())
				);
				userRoleList.forEach(m->{
					deptIds.add(m.getId());
                    DeptInfo deptInfo = deptInfoService.getBaseMapper().selectOne(new QueryWrapper<DeptInfo>().
                            eq("id", m.getId())
                    );
                    if (deptInfo!=null) {
                        deptName[0] =deptInfo.getName();
                    }
				});


			}
		}
		//Map<Integer, DeptInfo> deptMap = userRoleDeptTeamCacheService.getDeptMap(deptIds);
        String finalDeptName = deptName[0];
        IPage<UserModel> data=page.convert(new Function<UserInfo, UserModel>() {
			@Override
			public UserModel apply(UserInfo entity) {
				UserModel model = UserConvertUtils.getUserModel(entity);
				/*if (deptMap.containsKey(entity.getDeptId())) {
					model.setDeptName(deptMap.get(0).getName());
				}*/
                System.out.println("============="+finalDeptName+"======================");
                model.setDeptName(finalDeptName);
            /*    final List<AccountInfo> list = accountInfoService.list(new QueryWrapper<AccountInfo>().eq("user_id", entity.getId()).eq("state", 1));
                BigDecimal balance =new BigDecimal("0.00");
                BigDecimal point =new BigDecimal("0.00");
                list.forEach(m->{
                    if(Objects.equals("point",m.getFund())){
                        point.add(m.getFund());
                    }
                    if(Objects.equals("balance",m.getFund())){
                        balance.add(m.getFund());
                    }
                });
                model.setPoint(String.valueOf(point));
                model.setBalance(String.valueOf(balance));*/
				return UserConvertUtils.getUserModel(entity);
				
			}
		});
		return BaseResult.ok(data);
	}

	@PostMapping("/save")
    @StaffLogc(title = "User_Mgr_用户管理 、新增用户", action = "User_Mgr_用户管理、新增用户", actionAdo = "User_Mgr_用户管理")
	@ApiOperation(value="新增用户")
	public BaseResult save(@RequestBody UserRegisterParam params) {
		params.setSourceOne(UserOneSourceEnum.Admin_Reg.getCode());
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		params.setCompanyNo(userInfo.getCompanyNo());
		this._registerByUserName2Mobile(params);
		return BaseResult.ok();
	}


    @PostMapping("/update")
    @ApiOperation(value = "修改用户")
    @StaffLogc(title = "User_Mgr_用户管理 、修改用户", action = "User_Mgr_用户管理、修改用户", actionAdo = "User_Mgr_用户管理")
    public BaseResult update(@RequestBody UserMgrUpdateParam params) {
        ValidatorUtils.validate(params);
        userMgrService.update(params, AuthContextUtils.getUser());
        Set<Integer> userIds = new HashSet<>();
        userIds.add(params.getId());
        userPermissionCacheService.logoutUser(userIds);
        return BaseResult.ok();
    }

    @GetMapping("/get")
    @ApiOperation(value = "用户信息", response = UserModel.class)
    public BaseResult get(@RequestParam("id") Integer id) {
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfo == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        DeptInfo dept = null;
        if (CheckUtils.hasInt(userInfo.getDeptId())) {
            deptInfoService.getById(userInfo.getDeptId());
        }
        List<UserRoleInfo> userRoleList = userRoleInfoService.list(
                new QueryWrapper<UserRoleInfo>().eq("user_id", id)
        );
        dept = deptInfoService.getBaseMapper().selectOne(new QueryWrapper<DeptInfo>().
                eq("id", userInfo.getDeptId())
        );
        UserModel data = UserConvertUtils.getUserModel(userInfo, dept, userRoleList);
        return BaseResult.ok(data);
    }

    @PostMapping("/changeState")
    @StaffLogc(title = "User_Mgr_用户管理 、用户改变状态", action = "User_Mgr_用户管理、用户改变状态", actionAdo = "User_Mgr_用户管理")
    @ApiOperation(value = "用户改变状态", response = BaseResult.class)
    public BaseResult changeState(@RequestBody UserMgrUpdateStateParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        userMgrService.updateUserState(params.getId(), params.getState(), userInfo);
        return BaseResult.ok();
    }

    @PostMapping("/setPassWord")
    @StaffLogc(title = "User_Mgr_用户管理 、用户设置密码", action = "User_Mgr_用户管理、用户设置密码", actionAdo = "User_Mgr_用户管理")
    @ApiOperation(value = "用户设置密码", response = BaseResult.class)
    public BaseResult setPassWord(@RequestBody UserMgrUpdatePasswordParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        userMgrService.updateUserPassword(params.getId(), params.getPassword(), userInfo);
        return BaseResult.ok();
    }

    /**
     * 手机注册
     */
    private UserInfo _registerByUserName2Mobile(UserRegisterParam params) {
        ValidatorUtils.validate(params);
        params.setRegIp(HttpContextUtils.getClientIP());
        params.setRegWay(UserRegisterWayEnum.Reg_Mobile_UserName.getCode());
        UserInfo user = userRegisterService.register(params, null);
        return user;
    }


    

	/*@GetMapping("/delete")
	@ApiOperation(value="用户信息删除")
	public BaseResult delete(@RequestParam("code")Integer code) {
		UserInfo userInfo= userInfoService.getById(code);
		if(userInfo==null) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		userInfoService.updateById(userInfo);
		return BaseResult.ok();
	}*/

	




}
